#!/bin/bash
# 串口权限设置脚本
# 用途: 解决CH9344串口设备权限问题,确保重启后也能访问

set -e

echo "=== CH9344 串口权限设置脚本 ==="
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查是否以sudo运行
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}错误: 请使用 sudo 运行此脚本${NC}"
    echo "用法: sudo bash scripts/setup_serial_permissions.sh"
    exit 1
fi

echo "步骤 1: 检查CH9344驱动模块"
if lsmod | grep -q ch9344; then
    echo -e "${GREEN}✓${NC} ch9344 模块已加载"
else
    echo -e "${YELLOW}⚠${NC} ch9344 模块未加载,正在加载..."
    if modprobe ch9344 2>/dev/null; then
        echo -e "${GREEN}✓${NC} ch9344 模块加载成功"
    else
        echo -e "${RED}✗${NC} ch9344 模块加载失败"
        echo "提示: 可能需要先安装ch9344驱动"
    fi
fi
echo ""

echo "步骤 2: 设置模块开机自动加载"
if ! grep -q "^ch9344" /etc/modules 2>/dev/null; then
    echo "ch9344" >> /etc/modules
    echo -e "${GREEN}✓${NC} 已添加 ch9344 到 /etc/modules (开机自动加载)"
else
    echo -e "${GREEN}✓${NC} ch9344 已在 /etc/modules 中"
fi
echo ""

echo "步骤 3: 安装 udev 规则"
UDEV_RULES_FILE="/etc/udev/rules.d/99-ch9344.rules"
if [ -f "99-ch9344.rules" ]; then
    cp 99-ch9344.rules "$UDEV_RULES_FILE"
    chmod 644 "$UDEV_RULES_FILE"
    echo -e "${GREEN}✓${NC} udev 规则已安装到 $UDEV_RULES_FILE"
else
    echo -e "${RED}✗${NC} 找不到 99-ch9344.rules 文件"
    echo "提示: 请确保在项目根目录运行此脚本"
    exit 1
fi
echo ""

echo "步骤 4: 重新加载 udev 规则"
udevadm control --reload-rules
udevadm trigger --subsystem-match=tty
echo -e "${GREEN}✓${NC} udev 规则已重新加载"
echo ""

echo "步骤 5: 检查串口设备"
if ls /dev/ttyCH9344USB* >/dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} 找到 CH9344 串口设备:"
    ls -l /dev/ttyCH9344USB* | awk '{print "    " $0}'
    echo ""
    echo "设备权限信息:"
    for dev in /dev/ttyCH9344USB*; do
        perm=$(stat -c "%a" "$dev")
        owner=$(stat -c "%U:%G" "$dev")
        echo "    $dev - 权限:$perm 所有者:$owner"
    done
else
    echo -e "${YELLOW}⚠${NC} 未找到 CH9344 串口设备"
    echo "提示: 请检查:"
    echo "  1. USB转串口设备是否已连接"
    echo "  2. 运行 lsusb 查看USB设备"
    echo "  3. 运行 dmesg | tail -50 查看内核日志"
fi
echo ""

echo "步骤 6: 检查用户组"
CURRENT_USER=${SUDO_USER:-$USER}
if groups "$CURRENT_USER" | grep -q dialout; then
    echo -e "${GREEN}✓${NC} 用户 $CURRENT_USER 已在 dialout 组中"
else
    echo -e "${YELLOW}⚠${NC} 用户 $CURRENT_USER 不在 dialout 组中,正在添加..."
    usermod -a -G dialout "$CURRENT_USER"
    echo -e "${GREEN}✓${NC} 已将用户 $CURRENT_USER 添加到 dialout 组"
    echo -e "${YELLOW}注意: 需要重新登录才能生效${NC}"
fi
echo ""

echo "步骤 7: 创建测试脚本"
TEST_SCRIPT="/home/$CURRENT_USER/test_serial.sh"
cat > "$TEST_SCRIPT" <<'EOF'
#!/bin/bash
echo "=== 串口设备测试 ==="
echo ""
echo "1. CH9344 设备列表:"
ls -l /dev/ttyCH9344USB* 2>/dev/null || echo "   未找到设备"
echo ""
echo "2. 所有串口设备:"
ls -l /dev/tty{USB,ACM,CH9344}* 2>/dev/null || echo "   未找到设备"
echo ""
echo "3. USB设备列表 (1a86 = WCH/Jiangsu QinHeng):"
lsusb | grep -i "1a86" || echo "   未找到 WCH 设备"
echo ""
echo "4. 内核日志 (最近50行):"
dmesg | grep -i "ch9344\|tty" | tail -20
echo ""
echo "5. 当前用户组:"
groups
EOF
chmod +x "$TEST_SCRIPT"
chown "$CURRENT_USER:$CURRENT_USER" "$TEST_SCRIPT"
echo -e "${GREEN}✓${NC} 测试脚本已创建: $TEST_SCRIPT"
echo ""

echo "============================================"
echo -e "${GREEN}✅ 串口权限设置完成!${NC}"
echo "============================================"
echo ""
echo "📝 后续步骤:"
echo "  1. 重新插拔 USB 串口设备 (或重启系统)"
echo "  2. 运行测试脚本: bash $TEST_SCRIPT"
echo "  3. 如果仍然无法访问,请重新登录或重启系统"
echo ""
echo "🔍 故障排查:"
echo "  - 查看USB设备: lsusb"
echo "  - 查看内核日志: dmesg | grep ch9344"
echo "  - 查看串口设备: ls -l /dev/tty*"
echo "  - 手动加载模块: sudo modprobe ch9344"
echo ""
